package com.ylr.gateway.common.utils;

import com.ylr.base.common.enums.ResultEnum;
import com.ylr.base.common.exception.YlrException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;

import java.net.InetSocketAddress;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wei
 * date: 2021-03-15 00:00:00
 * className: IPUtils http请求ip地址获取工具类
 * version: 1.0
 * description:
 */
public class IPUtils {

    private static final Logger log = LoggerFactory.getLogger(IPUtils.class);

    /**
     * ipv4校验正则表达式
     */
    public static final String IPv4_REGEX = "^((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d).){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)$";

    /**
     * 获取IP地址
     * 使用Nginx等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址
     * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
     */
    public static String getRequestIp(ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        String ip = headers.getFirst("x-forwarded-for");
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("HTTP_CLIENT_IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("X-Real-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            InetSocketAddress remoteAddress = request.getRemoteAddress();
            if (Objects.nonNull(remoteAddress)) {
                ip = remoteAddress.getAddress().getHostAddress();
            }
        }
        // 使用代理，则获取第一个IP地址
        if(StringUtils.isNotEmpty(ip)) {
            int index = ip.indexOf(",");
            if (index > -1) {
                ip = ip.substring(0, index);
            }
        }
        if (!Pattern.matches(IPv4_REGEX, ip)) {
            log.error("请求源ip地址格式不正确，非正常请求。ip={}", ip);
            throw new YlrException(ResultEnum.ILLEGAL_FAIL);
        }
        return ip;
    }

}
